﻿function AzureTableQueryFuncExpressionModel(parentExpr, builderContext) {

    var self = this;

    var parent = ko.observable(parentExpr);

    var funcName = ko.observable();

    var arg = ko.observable();

    var canRemove = ko.computed(function () {
        return false;
    });

    var canAdd = ko.computed(function () {
        return true;
    });

    function removeExpr() {
    }

    function replaceChild(oldExpresison, newExpression) {
        arg(newExpression);
        newExpression.parent(self);
    }

    function addExpression() {
        var me = new AzureTableQueryCombineExpressionModel(parent, builderContext);
        parent().replaceChild(self, me);
        me.addChild(self);
        me.addChild(new AzureTableQueryCompareExpressionModel(me, builderContext));
    }

    function invert() {
        if (funcName() == 'not') {
            parent().replaceChild(self, arg());
        } else {
            var res = new AzureTableQueryFuncExpressionModel(parent(), builderContext);
            res.funcName('not');
            res.arg(self);
            parent().replaceChild(self, res);
        }
    }

    function highlight() {
        builderContext.highlightedExpression(self);
    }

    var queryString = ko.computed(function () {
        var res = '';
        res += funcName();

        var argument = arg();
        res += '(';
        res += argument ? argument.queryString() : '<argument>';
        res += ')';
        return res;
    });

    var queryHtmlString = ko.computed(function () {
        var res = '';
        res += funcName();

        var argument = arg();
        res += '(';
        res += argument ? argument.queryHtmlString() : '<span class="missing-value">&lt;argument&gt;</span>';
        res += ')';

        if (builderContext.highlightedExpression() == self) {
            res = '<span class="highlighted">' + res + '</span>';
        }

        return res;
    });

    self.type = 'func';

    self.parent = parent;
    self.funcName = funcName;
    self.arg = arg;
    self.canRemove = canRemove;
    self.canAdd = canAdd;
    self.invert = invert;
    self.removeExpr = removeExpr;
    self.replaceChild = replaceChild;
    self.addExpression = addExpression;
    self.highlight = highlight;
    self.queryString = queryString;
    self.queryHtmlString = queryHtmlString;
}